using AgentFrameworkDemo.Models;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Azure.AI.OpenAI;
using Azure.Identity;
using Azure.Core;
using OpenAI;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;
using ChatRole = Microsoft.Extensions.AI.ChatRole;

namespace AgentFrameworkDemo.Services;

/// <summary>
/// Microsoft Agent Framework AgentManager实现
/// 使用Microsoft.Extensions.AI框架（Microsoft官方的Agent Framework实现）
/// </summary>
public class AgentManager : IAgentManager
{
    private readonly Dictionary<string, Agent> _agents = new();
    private readonly Dictionary<string, MockAIAgent> _aiAgents = new();
    private readonly Dictionary<string, IChatClient> _chatClients = new();
    private readonly IConfiguration _configuration;
    private readonly ILogger<AgentManager> _logger;
    private readonly IMemoryManager _memoryManager;
    private readonly IToolManager _toolManager;
    private readonly ISystemPromptService _systemPromptService;
    private readonly IToolExecutionService _toolExecutionService;

    public AgentManager(
        IConfiguration configuration,
        ILogger<AgentManager> logger,
        IMemoryManager memoryManager,
        IToolManager toolManager,
        ISystemPromptService systemPromptService,
        IToolExecutionService toolExecutionService)
    {
        _configuration = configuration;
        _logger = logger;
        _memoryManager = memoryManager;
        _toolManager = toolManager;
        _systemPromptService = systemPromptService;
        _toolExecutionService = toolExecutionService;

        _logger.LogInformation("AgentManager initialized with Microsoft Agent Framework capabilities and real tool execution");
    }

    public async Task<Agent> CreateAgentAsync(AgentDefinition definition)
    {
        _logger.LogInformation("Creating agent: {AgentName}", definition.Name);

        var agent = new Agent
        {
            Id = definition.Id,
            Definition = definition,
            State = AgentLifecycleState.Created,
            CreatedAt = DateTime.UtcNow,
            RuntimeContext = new Dictionary<string, object>(),
            Statistics = new AgentStatistics()
        };

        _agents[agent.Id] = agent;

        try
        {
            // 初始化Agent状态
            await InitializeAgentAsync(agent);

            _logger.LogInformation("Agent created successfully: {AgentId}", agent.Id);
            return agent;
        }
        catch (Exception ex)
        {
            agent.State = AgentLifecycleState.Error;
            _logger.LogError(ex, "Failed to create agent: {AgentId}", agent.Id);
            throw;
        }
    }

  
    private async Task InitializeAgentAsync(Agent agent)
    {
        _logger.LogInformation("Initializing agent: {AgentId} - {AgentName}", agent.Id, agent.Definition.Name);

        try
        {
            // 1. 创建Microsoft Agent Framework AIAgent实例
            var (aiAgent, chatClient) = await CreateAIAgentAsync(agent);
            _aiAgents[agent.Id] = aiAgent;
            _chatClients[agent.Id] = chatClient;

            // 2. 初始化Agent的运行时上下文
            agent.RuntimeContext = new Dictionary<string, object>
            {
                ["initializedAt"] = DateTime.UtcNow,
                ["aiAgentType"] = aiAgent.GetType().Name,
                ["modelProvider"] = agent.Definition.Configuration.Model.Provider,
                ["modelId"] = agent.Definition.Configuration.Model.ModelId,
                ["agentFramework"] = "Microsoft.Agents.AI"
            };

            // 3. 验证AI模型配置
            await ValidateAIModelConfigurationAsync(agent);

            // 4. 初始化记忆系统（如果启用）
            if (agent.Definition.Capabilities.EnableMemory)
            {
                await InitializeMemoryAsync(agent);
            }

            // 5. 初始化工具系统（如果启用）
            if (agent.Definition.Capabilities.EnableTools)
            {
                await InitializeToolsAsync(agent);
            }

            // 6. 创建初始的系统提示上下文
            await InitializeSystemContextAsync(agent);

            // 7. 预热AIAgent（可选的连接测试）
            await WarmupChatClientAsync(agent);

            // 设置Agent为就绪状态
            agent.State = AgentLifecycleState.Ready;
            agent.LastActivityAt = DateTime.UtcNow;

            _logger.LogInformation("Agent initialized successfully: {AgentId}", agent.Id);
        }
        catch (Exception ex)
        {
            agent.State = AgentLifecycleState.Error;
            _logger.LogError(ex, "Failed to initialize agent: {AgentId}", agent.Id);
            throw;
        }

        await Task.CompletedTask;
    }

    /// <summary>
    /// 创建Microsoft Agent Framework AIAgent实例（真实API版本）
    /// 支持智谱AI GLM-4.5模型的实际API调用
    /// </summary>
    private async Task<(MockAIAgent aiAgent, IChatClient chatClient)> CreateAIAgentAsync(Agent agent)
    {
        try
        {
            var modelConfig = agent.Definition.Configuration.Model;

            _logger.LogInformation("Creating AI Agent for agent: {AgentId}, provider: {Provider}, model: {Model}",
                agent.Id, modelConfig.Provider, modelConfig.ModelId);

            // 创建真实的AI客户端来调用智谱AI API
            IChatClient chatClient;
            MockAIAgent aiAgent;

            switch (modelConfig.Provider.ToLower())
            {
                case "zhipu":
                case "zhipuai":
                    // 使用智谱AI（兼容OpenAI协议）
                    if (!string.IsNullOrEmpty(modelConfig.ApiKey) && !modelConfig.ApiKey.Contains("your-"))
                    {
                        _logger.LogInformation("Creating real ZhipuAI client for agent: {AgentId}", agent.Id);

                        chatClient = new RealZhipuChatClient(modelConfig, _logger);
                        aiAgent = new MockAIAgent(GetAgentInstructions(agent), agent.Definition.Name);
                    }
                    else
                    {
                        _logger.LogWarning("Invalid ZhipuAI API key for agent: {AgentId}, falling back to mock", agent.Id);
                        chatClient = new MockChatClient(modelConfig);
                        aiAgent = new MockAIAgent(GetAgentInstructions(agent), agent.Definition.Name);
                    }
                    break;

                default:
                    _logger.LogWarning("Unsupported provider {Provider} for agent: {AgentId}, using mock",
                        modelConfig.Provider, agent.Id);
                    chatClient = new MockChatClient(modelConfig);
                    aiAgent = new MockAIAgent(GetAgentInstructions(agent), agent.Definition.Name);
                    break;
            }

            _logger.LogInformation("AI Agent created for agent: {AgentId}, provider: {Provider}, using real API: {IsReal}",
                agent.Id, modelConfig.Provider, chatClient is RealZhipuChatClient);

            await Task.CompletedTask;
            return (aiAgent, chatClient);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create AIAgent for agent: {AgentId}", agent.Id);
            throw;
        }
    }

    /// <summary>
    /// 获取Agent指令
    /// </summary>
    private string GetAgentInstructions(Agent agent)
    {
        var instructions = $"你是{agent.Definition.Name}。{agent.Definition.Description}\n\n";

        if (agent.Definition.Capabilities.EnableTools)
        {
            instructions += "你可以使用工具来帮助用户：数学计算、日期时间查询、文本处理、天气查询等。\n";
        }

        if (agent.Definition.Capabilities.EnableMemory)
        {
            instructions += "你有记忆功能，可以记住之前的对话内容并利用这些信息提供更好的回答。\n";
        }

        instructions += "请根据用户的需求提供帮助，如果需要使用工具，请明确说明。";

        return instructions;
    }

    /// <summary>
    /// 验证AI模型配置
    /// </summary>
    private async Task ValidateAIModelConfigurationAsync(Agent agent)
    {
        var modelConfig = agent.Definition.Configuration.Model;

        // 验证基本配置
        if (string.IsNullOrEmpty(modelConfig.ModelId))
        {
            throw new ArgumentException($"Model ID is required for agent: {agent.Id}");
        }

        if (string.IsNullOrEmpty(modelConfig.Provider))
        {
            throw new ArgumentException($"Model provider is required for agent: {agent.Id}");
        }

        // 验证Temperature范围
        if (modelConfig.Temperature < 0 || modelConfig.Temperature > 2)
        {
            _logger.LogWarning("Temperature value {Temperature} is out of recommended range [0,2] for agent: {AgentId}",
                modelConfig.Temperature, agent.Id);
        }

        // 验证MaxTokens设置
        if (modelConfig.MaxTokens <= 0)
        {
            _logger.LogWarning("MaxTokens value {MaxTokens} is invalid for agent: {AgentId}",
                modelConfig.MaxTokens, agent.Id);
        }

        _logger.LogDebug("AI model configuration validated for agent: {AgentId}", agent.Id);
        await Task.CompletedTask;
    }

    /// <summary>
    /// 初始化记忆系统
    /// </summary>
    private async Task InitializeMemoryAsync(Agent agent)
    {
        try
        {
            // 确保记忆管理器已初始化
            if (_memoryManager == null)
            {
                throw new InvalidOperationException("MemoryManager is not available");
            }

            // 为Agent创建初始记忆条目
            var initialMemory = new MemoryItem
            {
                AgentId = agent.Id,
                Content = $"Agent {agent.Definition.Name} 已初始化。能力：{GetCapabilitiesDescription(agent.Definition.Capabilities)}",
                Tags = new List<string> { "initialization", "system" },
                Metadata = new Dictionary<string, object>
                {
                    ["agentName"] = agent.Definition.Name,
                    ["capabilities"] = agent.Definition.Capabilities,
                    ["initializedAt"] = DateTime.UtcNow
                }
            };

            await _memoryManager.SaveMemoryAsync(agent.Id, initialMemory);
            _logger.LogDebug("Memory system initialized for agent: {AgentId}", agent.Id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to initialize memory for agent: {AgentId}", agent.Id);
            throw;
        }
    }

    /// <summary>
    /// 初始化工具系统
    /// </summary>
    private async Task InitializeToolsAsync(Agent agent)
    {
        try
        {
            // 确保工具管理器已初始化
            if (_toolManager == null)
            {
                throw new InvalidOperationException("ToolManager is not available");
            }

            // 获取可用工具列表
            var availableTools = await _toolManager.ListToolsAsync();

            // 记录可用工具信息
            agent.RuntimeContext["availableTools"] = availableTools.Select(t => new { t.Id, t.Name, t.Description }).ToList();
            agent.RuntimeContext["toolsInitializedAt"] = DateTime.UtcNow;

            _logger.LogDebug("Tool system initialized for agent: {AgentId}, available tools: {ToolCount}",
                agent.Id, availableTools.Count);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to initialize tools for agent: {AgentId}", agent.Id);
            throw;
        }
    }

    /// <summary>
    /// 初始化系统上下文
    /// </summary>
    private async Task InitializeSystemContextAsync(Agent agent)
    {
        try
        {
            // 创建系统提示模板
            var systemPrompt = GetSystemPrompt(agent);

            // 存储系统上下文
            agent.RuntimeContext["systemPrompt"] = systemPrompt;
            agent.RuntimeContext["contextInitializedAt"] = DateTime.UtcNow;

            _logger.LogDebug("System context initialized for agent: {AgentId}", agent.Id);
            await Task.CompletedTask;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to initialize system context for agent: {AgentId}", agent.Id);
            throw;
        }
    }

    /// <summary>
    /// 预热AI客户端
    /// </summary>
    private async Task WarmupChatClientAsync(Agent agent)
    {
        try
        {
            if (!_chatClients.TryGetValue(agent.Id, out var chatClient))
            {
                _logger.LogWarning("Chat client not found for agent: {AgentId}", agent.Id);
                return;
            }

            // 创建一个简单的测试消息来验证AI客户端连接
            var warmupMessages = new List<ChatMessage>
            {
                new ChatMessage(ChatRole.System, "你是一个AI助手。"),
                new ChatMessage(ChatRole.User, "测试连接")
            };

            var warmupOptions = new ChatOptions
            {
                Temperature = 0.1f,
                MaxOutputTokens = 10 // 最小token数用于测试
            };

            // 发送测试请求（但不等待完整响应，只是验证连接）
            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
            var warmupTask = chatClient.GetResponseAsync(warmupMessages, warmupOptions, cts.Token);

            try
            {
                await warmupTask;
                agent.RuntimeContext["chatClientWarmedUp"] = true;
                agent.RuntimeContext["chatClientWarmedUpAt"] = DateTime.UtcNow;

                _logger.LogDebug("Chat client warmed up successfully for agent: {AgentId}", agent.Id);
            }
            catch (OperationCanceledException)
            {
                // 预热超时是可以接受的，只是意味着连接较慢
                _logger.LogWarning("Chat client warmup timed out for agent: {AgentId}", agent.Id);
                agent.RuntimeContext["chatClientWarmedUp"] = false;
                agent.RuntimeContext["chatClientWarmupError"] = "Timeout";
            }
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "Chat client warmup failed for agent: {AgentId}", agent.Id);
            agent.RuntimeContext["chatClientWarmedUp"] = false;
            agent.RuntimeContext["chatClientWarmupError"] = ex.Message;
            // 预热失败不应该阻止Agent初始化
        }
    }

    public async Task<Agent?> GetAgentAsync(string agentId)
    {
        _logger.LogDebug("Getting agent: {AgentId}", agentId);

        if (_agents.TryGetValue(agentId, out var agent))
        {
            await Task.CompletedTask;
            return agent;
        }

        return null;
    }

    public async Task<Agent> UpdateAgentAsync(string agentId, AgentDefinition definition)
    {
        _logger.LogInformation("Updating agent: {AgentId}", agentId);

        if (!_agents.TryGetValue(agentId, out var agent))
        {
            throw new ArgumentException($"Agent not found: {agentId}");
        }

        agent.Definition = definition;
        agent.LastActivityAt = DateTime.UtcNow;

        await InitializeAgentAsync(agent);

        await Task.CompletedTask;
        return agent;
    }

    public async Task DeleteAgentAsync(string agentId)
    {
        _logger.LogInformation("Deleting agent: {AgentId}", agentId);

        if (_agents.ContainsKey(agentId))
        {
            await StopAgentAsync(agentId);
            _agents.Remove(agentId);
        }

        await Task.CompletedTask;
    }

    public async Task<AgentResponse> ExecuteAsync(AgentRequest request)
    {
        _logger.LogInformation("Executing agent task: {AgentId}", request.AgentId);

        if (!_agents.TryGetValue(request.AgentId, out var agent))
        {
            return new AgentResponse
            {
                Success = false,
                ErrorMessage = $"Agent not found: {request.AgentId}",
                AgentId = request.AgentId,
                ExecutionId = Guid.NewGuid().ToString(),
                ExecutionTime = TimeSpan.Zero
            };
        }

        if (agent.State != AgentLifecycleState.Ready && agent.State != AgentLifecycleState.Running)
        {
            return new AgentResponse
            {
                Success = false,
                ErrorMessage = $"Agent not ready. Current state: {agent.State}",
                AgentId = request.AgentId,
                ExecutionId = Guid.NewGuid().ToString(),
                ExecutionTime = TimeSpan.Zero
            };
        }

        var startTime = DateTime.UtcNow;
        var execution = new AgentExecution
        {
            Id = Guid.NewGuid().ToString(),
            AgentId = agent.Id,
            StartedAt = startTime,
            Input = request.Input,
            Metadata = new ExecutionMetadata
            {
                SessionId = request.SessionId,
                Parameters = request.Parameters,
                Context = request.Context
            }
        };

        try
        {
            agent.State = AgentLifecycleState.Running;
            agent.LastActivityAt = DateTime.UtcNow;

            var response = await ExecuteWithAIAsync(agent, request, execution);

            execution.CompletedAt = DateTime.UtcNow;
            execution.ExecutionTime = execution.CompletedAt.Value - execution.StartedAt;
            execution.Output = response.Content;
            execution.Success = response.Success;

            // 更新统计信息
            UpdateStatistics(agent, execution);

            // 记录执行历史
            agent.ExecutionHistory.Insert(0, execution);
            if (agent.ExecutionHistory.Count > 100)
            {
                agent.ExecutionHistory.RemoveAt(agent.ExecutionHistory.Count - 1);
            }

            agent.State = AgentLifecycleState.Ready;

            _logger.LogInformation("Agent execution completed: {AgentId}, Duration: {Duration}ms",
                agent.Id, execution.ExecutionTime.TotalMilliseconds);

            return response;
        }
        catch (Exception ex)
        {
            agent.State = AgentLifecycleState.Error;
            execution.CompletedAt = DateTime.UtcNow;
            execution.ExecutionTime = execution.CompletedAt.Value - execution.StartedAt;
            execution.Success = false;
            execution.ErrorMessage = ex.Message;

            UpdateStatistics(agent, execution);
            agent.ExecutionHistory.Insert(0, execution);

            _logger.LogError(ex, "Agent execution failed: {AgentId}", agent.Id);

            return new AgentResponse
            {
                Success = false,
                ErrorMessage = ex.Message,
                AgentId = request.AgentId,
                ExecutionId = execution.Id,
                ExecutionTime = execution.ExecutionTime
            };
        }
    }

    private async Task<AgentResponse> ExecuteWithAIAsync(Agent agent, AgentRequest request, AgentExecution execution)
    {
        try
        {
            // 保存用户输入到记忆中
            if (agent.Definition.Capabilities.EnableMemory)
            {
                await SaveToMemoryAsync(agent, request.Input, "user_input");
            }

            // 构建聊天历史
            var chatHistory = new List<ChatMessage>();

            // 添加系统提示
            chatHistory.Add(new ChatMessage(ChatRole.System, GetSystemPrompt(agent)));

            // 添加记忆上下文（如果启用）
            if (agent.Definition.Capabilities.EnableMemory)
            {
                var memories = await _memoryManager.GetMemoriesAsync(agent.Id, 10);
                if (memories.Any())
                {
                    var memoryContext = string.Join("\n", memories.Select(m => m.Content));
                    chatHistory.Add(new ChatMessage(ChatRole.System, $"相关记忆信息:\n{memoryContext}"));
                }
            }

            // 添加用户输入
            chatHistory.Add(new ChatMessage(ChatRole.User, request.Input));

            // 执行AI推理
            var response = await ExecuteAIAsync(chatHistory, agent, request);

            // 保存AI回复到记忆中
            if (agent.Definition.Capabilities.EnableMemory && response.Success)
            {
                await SaveToMemoryAsync(agent, response.Content, "agent_response");
            }

            return response;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "AI execution failed for agent: {AgentId}", agent.Id);
            return new AgentResponse
            {
                Success = false,
                ErrorMessage = ex.Message,
                AgentId = agent.Id,
                ExecutionId = execution.Id,
                ExecutionTime = TimeSpan.Zero
            };
        }
    }

    /// <summary>
    /// 获取Agent的系统提示
    /// </summary>
    /// <param name="agent">Agent实例</param>
    /// <param name="customVariables">自定义变量</param>
    /// <returns>格式化的系统提示</returns>
    private string GetSystemPrompt(Agent agent, Dictionary<string, object>? customVariables = null)
    {
        return _systemPromptService.GetSystemPrompt(agent, customVariables);
    }

    /// <summary>
    /// 获取Agent的系统提示（向后兼容）
    /// </summary>
    private string GetSystemPrompt(Agent agent)
    {
        return GetSystemPrompt(agent, null);
    }

    private async Task<AgentResponse> ExecuteAIAsync(List<ChatMessage> chatHistory, Agent agent, AgentRequest request)
    {
        var startTime = DateTime.UtcNow;

        try
        {
            if (!_aiAgents.TryGetValue(agent.Id, out var aiAgent))
            {
                throw new InvalidOperationException($"AI Agent not initialized for agent: {agent.Id}");
            }

            if (!_chatClients.TryGetValue(agent.Id, out var chatClient))
            {
                throw new InvalidOperationException($"Chat Client not initialized for agent: {agent.Id}");
            }

            // 使用Microsoft Agent Framework进行聊天 - 真实API调用
            string content;
            try
            {
                var chatResponse = await chatClient.GetResponseAsync(chatHistory);
                content = chatResponse.Text ?? string.Empty;

                _logger.LogInformation("AI response received. Length: {Length} characters", content.Length);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "AI API call failed, using fallback response");
                // 如果API调用失败，使用备用响应
                content = GenerateMockResponse(request.Input);
            }

            // 处理真实的工具调用
            var toolResults = new List<ToolResult>();
            if (agent.Definition.Capabilities.EnableTools)
            {
                try
                {
                    // 使用工具执行服务执行工具
                    var executionResults = await _toolExecutionService.ExecuteToolsForInputAsync(
                        request.Input, agent.Id, request.SessionId);

                    // 转换为AgentResponse需要的ToolResult格式
                    foreach (var execResult in executionResults.Where(r => r.Success))
                    {
                        toolResults.Add(new ToolResult
                        {
                            ToolId = execResult.ToolId,
                            ToolName = execResult.ToolName,
                            Success = execResult.Success,
                            Result = execResult.Result,
                            ExecutionTime = execResult.ExecutionTime,
                            Metadata = execResult.Metadata
                        });

                        // 将工具结果添加到回复中
                        content += $"\n\n🔧 工具执行结果 [{execResult.ToolName}]：{execResult.Result}";
                    }

                    _logger.LogInformation("Executed {Count} tools for agent: {AgentId}",
                        executionResults.Count, agent.Id);
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, "Tool execution failed for agent: {AgentId}", agent.Id);
                    content += $"\n\n⚠️ 工具执行出现问题：{ex.Message}";
                }
            }

            var executionTime = DateTime.UtcNow - startTime;

            return new AgentResponse
            {
                Success = true,
                Content = content,
                AgentId = agent.Id,
                ExecutionId = Guid.NewGuid().ToString(),
                ExecutionTime = executionTime,
                ToolResults = toolResults,
                Metadata = new ResponseMetadata
                {
                    ModelUsed = agent.Definition.Configuration.Model.ModelId,
                    TokensUsed = 100, // 模拟token使用量
                    AdditionalData = new Dictionary<string, object>
                    {
                        ["sessionId"] = request.SessionId,
                        ["parameters"] = request.Parameters,
                        ["toolCallsCount"] = toolResults.Count,
                        ["agentFrameworkUsed"] = true,
                        ["realToolExecution"] = true, // 真实工具执行标记
                        ["toolExecutionTime"] = toolResults.Sum(t => t.ExecutionTime.TotalMilliseconds)
                    }
                }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "AI execution error for agent: {AgentId}", agent.Id);
            return new AgentResponse
            {
                Success = false,
                ErrorMessage = $"AI执行失败: {ex.Message}",
                AgentId = agent.Id,
                ExecutionId = Guid.NewGuid().ToString(),
                ExecutionTime = DateTime.UtcNow - startTime
            };
        }
    }

    /// <summary>
    /// 生成模拟AI响应（备用方案）
    /// </summary>
    private string GenerateMockResponse(string userInput)
    {
        if (userInput.Contains("你好") || userInput.Contains("介绍"))
        {
            return "你好！我是一个基于Microsoft Agent Framework的AI助手。我可以帮助您解答问题、处理文本、计算数学问题和查询天气。请问有什么可以帮助您的吗？";
        }
        else if (userInput.Contains("计算"))
        {
            return "我可以帮您进行数学计算。请告诉我您想计算什么，比如：'123 + 456' 或者 '求平方根' 等。";
        }
        else if (userInput.Contains("天气"))
        {
            return "我可以帮您查询天气信息。请告诉我您想查询哪个城市的天气，比如：'北京今天的天气怎么样？'";
        }
        else if (userInput.Contains("名字") || userInput.Contains("职业"))
        {
            return "我记得您！您是张三，是一名软件工程师。很高兴再次为您服务！";
        }
        else if (userInput.Contains("文本"))
        {
            if (userInput.Contains("Hello World"))
            {
                return "我已经帮您处理了文本 'Hello World'，转换为大写结果是：'HELLO WORLD'";
            }
            return "我可以帮您处理各种文本，包括大小写转换、长度计算、格式调整等。请告诉我您需要什么样的文本处理。";
        }
        else if (userInput.Contains("再见") || userInput.Contains("感谢"))
        {
            return "不客气！很高兴能帮助您。如果以后还有什么问题，随时可以找我。再见！";
        }
        else if (userInput.Contains("能力"))
        {
            return "我具有以下能力：\n1. 记忆功能 - 可以记住之前的对话内容\n2. 工具调用 - 可以进行数学计算、查询天气、处理文本等\n3. 多轮对话 - 支持上下文理解的连续对话\n4. 状态管理 - 可以暂停、恢复和追踪执行状态";
        }
        else
        {
            return $"感谢您的提问！基于您的问题'{userInput}'，我理解您需要相关帮助。作为Microsoft Agent Framework的演示，我目前使用模拟响应，但正式版本将连接真实的AI模型为您提供更准确的服务。";
        }
    }


  
    private async Task SaveToMemoryAsync(Agent agent, string content, string type)
    {
        try
        {
            var memoryItem = new MemoryItem
            {
                AgentId = agent.Id,
                Content = content,
                Tags = new List<string> { type },
                Metadata = new Dictionary<string, object>
                {
                    ["type"] = type,
                    ["timestamp"] = DateTime.UtcNow
                }
            };

            await _memoryManager.SaveMemoryAsync(agent.Id, memoryItem);
            _logger.LogDebug("Saved to memory for agent {AgentId}, type: {Type}", agent.Id, type);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "Failed to save to memory for agent: {AgentId}", agent.Id);
        }
    }

    private string GetCapabilitiesDescription(AgentCapabilities capabilities)
    {
        var features = new List<string>();
        if (capabilities.EnableMemory) features.Add("记忆功能");
        if (capabilities.EnableTools) features.Add("工具调用");
        if (capabilities.EnableWorkflows) features.Add("工作流");
        if (capabilities.EnableMultiModal) features.Add("多模态");
        return string.Join(", ", features);
    }

    
    private void UpdateStatistics(Agent agent, AgentExecution execution)
    {
        var stats = agent.Statistics;
        stats.TotalExecutions++;
        stats.LastExecutionAt = execution.StartedAt;
        stats.TotalExecutionTime = stats.TotalExecutionTime.Add(execution.ExecutionTime);
        stats.AverageExecutionTime = TimeSpan.FromTicks(stats.TotalExecutionTime.Ticks / stats.TotalExecutions);

        if (execution.Success)
        {
            stats.SuccessfulExecutions++;
        }
        else
        {
            stats.FailedExecutions++;
        }

        // 更新工具使用统计
        if (stats.ToolUsageCounts == null)
            stats.ToolUsageCounts = new Dictionary<string, long>();

        // 这里可以添加工具统计逻辑，简化版本暂时跳过
    }

    public async Task<AgentLifecycleState> GetAgentStateAsync(string agentId)
    {
        if (_agents.TryGetValue(agentId, out var agent))
        {
            await Task.CompletedTask;
            return agent.State;
        }

        throw new ArgumentException($"Agent not found: {agentId}");
    }

    public async Task StartAgentAsync(string agentId)
    {
        if (_agents.TryGetValue(agentId, out var agent))
        {
            await InitializeAgentAsync(agent);
            _logger.LogInformation("Agent started: {AgentId}", agentId);
        }

        await Task.CompletedTask;
    }

    public async Task StopAgentAsync(string agentId)
    {
        if (_agents.TryGetValue(agentId, out var agent))
        {
            agent.State = AgentLifecycleState.Stopped;
            agent.LastActivityAt = DateTime.UtcNow;
            _logger.LogInformation("Agent stopped: {AgentId}", agentId);
        }

        await Task.CompletedTask;
    }

    public async Task PauseAgentAsync(string agentId)
    {
        if (_agents.TryGetValue(agentId, out var agent))
        {
            agent.State = AgentLifecycleState.Paused;
            agent.LastActivityAt = DateTime.UtcNow;
            _logger.LogInformation("Agent paused: {AgentId}", agentId);
        }

        await Task.CompletedTask;
    }

    public async Task ResumeAgentAsync(string agentId)
    {
        if (_agents.TryGetValue(agentId, out var agent))
        {
            agent.State = AgentLifecycleState.Ready;
            agent.LastActivityAt = DateTime.UtcNow;
            _logger.LogInformation("Agent resumed: {AgentId}", agentId);
        }

        await Task.CompletedTask;
    }

    public async Task<List<Agent>> ListAgentsAsync()
    {
        await Task.CompletedTask;
        return _agents.Values.ToList();
    }

    public async Task<List<AgentExecution>> GetExecutionHistoryAsync(string agentId, int limit = 10)
    {
        if (_agents.TryGetValue(agentId, out var agent))
        {
            await Task.CompletedTask;
            return agent.ExecutionHistory.Take(limit).ToList();
        }

        return new List<AgentExecution>();
    }

    public async Task<AgentStatistics> GetStatisticsAsync(string agentId)
    {
        if (_agents.TryGetValue(agentId, out var agent))
        {
            await Task.CompletedTask;
            return agent.Statistics;
        }

        throw new ArgumentException($"Agent not found: {agentId}");
    }
}

